package com.detech.sbom.base.satoken.config;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.jwt.StpLogicJwtForSimple;
import cn.dev33.satoken.stp.StpLogic;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.detech.sbom.base.constant.CacheConstants;
import com.detech.sbom.base.constant.ConstantsCookie;
import com.detech.sbom.base.exception.ServiceException;
import com.detech.sbom.base.redis.RedisUtils;
import com.detech.sbom.base.satoken.properties.SaTokenCustomProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * Sa-Token 配置
 */
@Configuration
public class SaTokenConfiguration implements WebMvcConfigurer {

    @Resource
    SaTokenCustomProperties saTokenCustom;
    @Autowired
    private HttpServletRequest request;

    // Sa-Token 整合 jwt (Simple 简单模式)
    @Bean
    public StpLogic getStpLogicJwt() {
        return new StpLogicJwtForSimple();
    }

    /**
     * 注册sa-token的拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 全局登录拦截器，并打开注解鉴权功能
        registry.addInterceptor(new SaInterceptor(handle -> StpUtil.checkLogin()))
            //拦截路径
            .addPathPatterns("/**")
            //白名单
            .excludePathPatterns(saTokenCustom.getLoginCheckIgnore());

        //全局验证码拦截
        if(saTokenCustom.getValidateCodeEnable()){
            registry.addInterceptor(new SaInterceptor(handle -> checkCaptcha()))
                    //拦截路径
                    .addPathPatterns(saTokenCustom.getValidateCodeFilter())
            ;
        }

        // 路由鉴权，可自定义详细认证规则
//        registry.addInterceptor(new SaInterceptor(handler -> {
//            // 根据路由划分模块，不同模块不同鉴权
//            SaRouter.match("/user/**", r -> StpUtil.checkPermission("user"));
//            SaRouter.match("/admin/**", r -> StpUtil.checkPermission("admin"));
//            SaRouter.match("/goods/**", r -> StpUtil.checkPermission("goods"));
//            SaRouter.match("/orders/**", r -> StpUtil.checkPermission("orders"));
//            SaRouter.match("/notice/**", r -> StpUtil.checkPermission("notice"));
//            SaRouter.match("/comment/**", r -> StpUtil.checkPermission("comment"));
//        }));
    }

    /**
     * 验证码检查
     */
    private void checkCaptcha(){
        String code = request.getHeader(ConstantsCookie.YZM);
        if(StrUtil.isBlank(code)){
            code = request.getParameter(ConstantsCookie.YZM);
        }
        String sessionid = request.getSession().getId();
        if (StrUtil.isEmpty(code)) {
            throw new ServiceException("验证码不能为空！");
        }
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + sessionid;
        String captcha = RedisUtils.getCacheObject(verifyKey);
        RedisUtils.deleteObject(verifyKey);

        if (!code.equalsIgnoreCase(captcha)) {
            throw new ServiceException("验证码错误！");
        }
    }
}
